package com.sample.dao.impl;

import java.util.List;

import org.hibernate.criterion.Restrictions;

import com.sample.dao.UserDAO;
import com.sample.model.User;
import com.sample.model.UserProject;

public class UserDAOImpl extends BaseGenericDAO<User, Long> implements UserDAO {

	@Override
	public void create(User user) {
		super.create(user);
		
		if (user.getProjects() != null) {
			for (UserProject userProject : user.getProjects()) {
				if (userProject.getBillRate() != null && userProject.getBillRate().isNaN()) {
					userProject.setBillRate(null);
				}
				userProject.setUser(user);
				
				userProject.setId(null);
				getSession().save(userProject);
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(User user) {
		super.update(user);
		
		flush();
		
		List<UserProject> prev = getSession().createCriteria(UserProject.class)
				.add(Restrictions.eq("user.id", user.getId())).list();
		
		if (user.getProjects() == null) {
			user.setProjects(prev);
		} else {
outerLoop:	for (UserProject userProject : user.getProjects()) {
				if (userProject.getBillRate() != null && userProject.getBillRate().isNaN()) {
					userProject.setBillRate(null);
				}
				userProject.setUser(user);
				
				for (int i = 0; i < prev.size(); i++) {
					UserProject prevUP = prev.get(i);
					if (prevUP.getProject().getId().equals( userProject.getProject().getId() ) ) {
						prevUP.setBillRate(userProject.getBillRate());
						prevUP.setStartDate(userProject.getStartDate());
						prevUP.setEndDate(userProject.getEndDate());
						prev.remove(i);
						//found
						continue outerLoop;
					}
				}

				//else, not found
				userProject.setId(null);
				getSession().save(userProject);
			}
			
			for (int i = 0; i < prev.size(); i++) {
				getSession().delete(prev.get(i));
			}
		}
	}

}